//
//  Lib.m
//  MHO
//
//  Created by papo on 2/17/14.
//  Copyright (c) 2014 maihoang. All rights reserved.
//

#import "Lib.h"
//#import "m"
#import "MMProgressHUD.h"
#import <Social/Social.h>
#import <CommonCrypto/CommonDigest.h>
#import "IPDetector.h"



#define kLoadingViewTag 97312
#define kUserLoginBool  @"loginkey"

#define kAppVersion 14

@implementation Lib

+ (BOOL)isUserLogin {
    return [[Lib stringForKey:kUserLoginBool] boolValue];
}

+ (void)setUserLogin:(BOOL)login {
    [Lib setString:[NSString stringWithFormat:@"%d", login] forKey:kUserLoginBool];
}

+ (void)showLoadingView {
    [MMProgressHUD setPresentationStyle:MMProgressHUDPresentationStyleFade];
    [MMProgressHUD showWithTitle:@"Đang tải"];
}

+ (void)removeLoadingView{
    [MMProgressHUD dismiss];
}

+ (NSString*)getServiceId {
    return @"200001";
}

+ (NSString*)getServiceKey {
    return @"BE543DBC2336";
}

+ (void)setString:(NSString *)string forKey:(NSString *)key {
    NSUserDefaults* dt = [NSUserDefaults standardUserDefaults];
    NSMutableData *data = [[NSMutableData alloc] init];
	NSKeyedArchiver *encoder = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
	
	[encoder encodeObject:string forKey:@"keyencode"];
	[encoder finishEncoding];
	[dt setObject:data forKey:key];
	[dt synchronize];
}

+ (NSString*)stringForKey:(NSString *)key {
    NSUserDefaults *pref = [NSUserDefaults standardUserDefaults];
    NSMutableData *data = [pref objectForKey:key];
    
    NSKeyedUnarchiver *decoder = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
    NSString* string = [decoder decodeObjectForKey:@"keyencode"];
    
    return string;
}


+ (void)showMessage:(NSString*)message title:(NSString*)title {
    UIAlertView* alert = [[UIAlertView alloc] initWithTitle:title message:message delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
    [alert show];
}

+ (BOOL)isIos7 {
    return [[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0;
}

+ (CGFloat)textViewHeightForAttributedText:(NSAttributedString *)text andWidth:(CGFloat)width
{
    UITextView *textView = [[UITextView alloc] init];
    [textView setAttributedText:text];
    CGSize size = [textView sizeThatFits:CGSizeMake(width, FLT_MAX)];
    return size.height;
}

+ (CGSize)text:(NSString *)text sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size
{
    if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7.0"))
    {
        CGRect frame = [text boundingRectWithSize:size
                                          options:(NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading)
                                       attributes:@{NSFontAttributeName:font}
                                          context:nil];
        return frame.size;
    }
    else
    {
        return [text sizeWithFont:font constrainedToSize:size];
    }
}

+ (NSString*)getDocumentPath {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
    return basePath;
}

+ (UIColor*)colorFromHexString:(NSString *)color alpha:(CGFloat)alpha {
    unsigned rgbValue = 0;
    NSScanner *scanner = [NSScanner scannerWithString:color];
    [scanner setScanLocation:1]; // bypass '#' character
    [scanner scanHexInt:&rgbValue];

    return UIColorFromRGBA(rgbValue, alpha);
}

+ (UIColor*)colorFromHexString:(NSString *)color {
    return [self colorFromHexString:color alpha:1.0];
}

+ (void)shareFacebook:(NSString *)content {
    if([SLComposeViewController isAvailableForServiceType:SLServiceTypeFacebook]) {
        SLComposeViewController *controller = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeFacebook];

        [controller setInitialText:content];
        [[self getRootViewController] presentViewController:controller animated:YES completion:Nil];
    }
    else {
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"" message:@"Bạn chưa đăng nhập Facebook! Hãy vào Setting/Facebook đăng nhập để sử dụng chức năng này!" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
    }
}

+ (UIViewController*)getRootViewController {
    UIWindow* window = [[UIApplication sharedApplication] keyWindow];
    if (!window) {
        NSArray* array = [[UIApplication sharedApplication] windows];
        window = array[0];
    }

    return [window rootViewController];
}

+ (void)checkUpdate {
//    [self showLoadingView];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSString* url = [NSString stringWithFormat:@"http://mobile.mho.vn/services/updateApp?Idsystem=4&key=%@", kServerKey];
        NSString* retV = [ServiceLib sendGetRequest:url useCache:NO];
        if (retV) {
            SBJsonParser* parser = [[SBJsonParser alloc] init];
            id dict = [parser objectWithString:retV];
            if (dict) {
                NSNumber* version = [dict objectForKey:@"Version"];
                NSString* link = [dict objectForKey:@"Link"];
                float currentVersion = [[NSUserDefaults standardUserDefaults] floatForKey:@"currentVersion"];
                
                if (currentVersion == 0) {
                    currentVersion = kAppVersion;
                }
                
                if ([version floatValue] > currentVersion) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [UIAlertView showWithTitle:@"Thông báo" message:@"Có một phiên bản mới! Bạn có muốn cập nhật không?" cancelButtonTitle:@"Không" otherButtonTitles:@[@"Có"] tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
                            if (buttonIndex == 1) {
                                [[NSUserDefaults standardUserDefaults] setFloat:version.floatValue forKey:@"currentVersion"];
                                [[NSUserDefaults standardUserDefaults] synchronize];
                                NSLog(@"Link version: %@", link);
                                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"itms-services://?action=download-manifest&url=%@", link]]];
                                // @"https://dl.dropboxusercontent.com/s/lzjk3jwlehrrnam/MHO.plist?dl=0"
                            }
                            else {
                                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"itms-services://?action=download-manifest&url=%@", @"https://dl.dropboxusercontent.com/s/lzjk3jwlehrrnam/MHO.plist"]]];
                            }
                        }];
                    });
                }
            }
        }
    });
}

+ (void)installApp:(TCBlobDownloader *)downloader {
    Application* app = downloader.app;
    NSString* fileName;
    if (downloader.fileName) {
        fileName = [downloader.fileName lastPathComponent];
    }
    else {
        fileName = [app.file lastPathComponent];
    }
    NSString* plist = [fileName stringByDeletingPathExtension];
    plist = [plist stringByAppendingPathExtension:@"plist"];
    NSString* downloadPath = [[TCBlobDownloadManager sharedInstance] defaultDownloadPath];
//    fileName = [downloadPath stringByAppendingPathComponent:fileName];
//    plist = [downloadPath stringByAppendingPathComponent:plist];
    NSString* ipaFile = [downloadPath stringByAppendingPathComponent:fileName];
    NSString* desfile = [[self getDocumentPath] stringByAppendingPathComponent:fileName];
    if (![[NSFileManager defaultManager] fileExistsAtPath:desfile ]) {
        [[NSFileManager defaultManager] copyItemAtPath:ipaFile toPath:desfile error:nil];
    }
    
    BOOL isDirectory;
    NSString* plistFile = [[self getDocumentPath] stringByAppendingPathComponent:plist];
    if ([[NSFileManager defaultManager] fileExistsAtPath:plistFile isDirectory:&isDirectory]) {
        [[NSFileManager defaultManager] removeItemAtPath:plistFile error:nil];
    }
    {
        // assets
        NSMutableDictionary* asset0 = [NSMutableDictionary dictionary];
        NSString* localFile = [NSString stringWithFormat:@"http://localhost:8080/%@", fileName];
        
        [asset0 setObject:localFile forKey:@"url"];
        [asset0 setObject:@"software-package" forKey:@"kind"];
        
        NSMutableDictionary* asset1 = [NSMutableDictionary dictionary];
        [asset1 setObject:@"display-image" forKey:@"kind"];
        [asset1 setObject:@"" forKey:@"url"];
        [asset1 setObject:@NO forKey:@"needs-shine"];
        NSArray* assets = @[asset0, asset1];
        
        // mettadata
        NSMutableDictionary* metadata = [NSMutableDictionary dictionary];
        [metadata setObject:@"com.game.abc" forKey:@"bundle-identifier"];
        [metadata setObject:@"software" forKey:@"kind"];
        [metadata setObject:app.appName forKey:@"title"];
//        [metadata setObject:app.versionApp forKey:@"version"];
        
        NSMutableDictionary* item0 = [NSMutableDictionary dictionary];
        [item0 setObject:assets forKey:@"assets"];
        [item0 setObject:metadata forKey:@"metadata"];
        
        NSMutableDictionary* root = [NSMutableDictionary dictionary];
        [root setObject:@[item0] forKey:@"items"];
        
        [root writeToFile:plistFile atomically:YES];
    }
//    plist = [NSString stringWithFormat:@"https://localhost:8080/%@", plist];
    plist = app.plist;
    plist = @"https://dl.dropboxusercontent.com/s/fg6kaiub841t87e/test.SL0Q.plist";
    NSURL* url = [NSURL URLWithString:[NSString stringWithFormat:@"itms-services://?action=download-manifest&url=%@", plist]];

    [[UIApplication sharedApplication] openURL:url];
}

+ (unsigned long long)sizeOfFolder:(NSString *)folder {
    NSError *attributesError = nil;
//
//    NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:folder error:&attributesError];
//    
//    unsigned long long fileSize = [fileAttributes fileSize];
//    NSLog(@"folder %@ size: %@ error: %@", folder, fileAttributes, attributesError);
//    return fileSize;
    
    NSArray *filesArray = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:folder error:nil];
    NSEnumerator *filesEnumerator = [filesArray objectEnumerator];
    NSString *fileName;
    unsigned long long int fileSize = 0;
    
    while (fileName = [filesEnumerator nextObject]) {
        NSDictionary *fileDictionary = [[NSFileManager defaultManager] attributesOfItemAtPath:[folder stringByAppendingPathComponent:fileName] error:&attributesError];
        fileSize += [fileDictionary fileSize];
    }
    
    return fileSize;
}

+ (unsigned long long)sizeOfFile:(NSString *)file {
    NSError* attributesError;
    NSDictionary *fileDictionary = [[NSFileManager defaultManager] attributesOfItemAtPath:file error:&attributesError];
    return [fileDictionary fileSize];
}

+ (NSString *) md5:(NSString *) input
{
    const char *cStr = [input UTF8String];
    unsigned char digest[16];
    CC_MD5( cStr, (unsigned int)strlen(cStr), digest ); // This is the md5 call
    
    NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    
    for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
        [output appendFormat:@"%02x", digest[i]];
    
    return  output;
    
}

+ (void)getWANIPAddressWithCompletion:(void (^)(NSString *))completion {
    [IPDetector getWANIPAddressWithCompletion:completion];
}


@end

//
